package com.jinyu.jyly.ui.mine.setting;

import android.Manifest;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseActivity;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.UpdateInfo;
import com.jinyu.jyly.global.GlobalConstants;
import com.jinyu.jyly.ui.login.LoginActivity;
import com.jinyu.jyly.ui.mine.setting.changemobile.ChangeMobile01Activity;
import com.jinyu.jyly.ui.mine.setting.login_psw.LoginPswActivity;
import com.jinyu.jyly.ui.mine.setting.login_psw.TranPswActivity;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.utils.APKVersionCodeUtils;
import com.jinyu.jyly.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import util.UpdateAppUtils;

/**
 * 设置页面
 */
public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.View {

    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_title_view)
    RelativeLayout rlTitleView;
    @BindView(R.id.iv_header)
    RoundedImageView ivHeader;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.ll_nickname)
    LinearLayout llNickname;
    @BindView(R.id.ll_mobile)
    LinearLayout llMobile;
    @BindView(R.id.ll_login_psw)
    LinearLayout llLoginPsw;
    @BindView(R.id.ll_jiaoyi_psw)
    LinearLayout llJiaoyiPsw;
    @BindView(R.id.ll_huancun)
    LinearLayout llHuancun;
    @BindView(R.id.ll_about)
    LinearLayout llAbout;
    @BindView(R.id.ll_version)
    LinearLayout llVersion;
    @BindView(R.id.btn_sub)
    Button btnSub;
    @BindView(R.id.tv_version_name)
    TextView tv_version_name;

    private SettingPresenter presenter;
    private String mobile;
    private String realname;
    private String head_pic;
    private int themeId;
    private int mVersionCode;

    @Override
    public int getLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected SettingPresenter getPresenter() {
        if (presenter == null) {
            presenter = new SettingPresenter(this, this);
        }
        return presenter;
    }

    @Override
    protected void initEventAndData() {
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        String versionname = APKVersionCodeUtils.getVerName(this);
        mVersionCode = APKVersionCodeUtils.getVersionCode(this);
        tv_version_name.setText("V"+versionname);

        mobile = getIntent().getStringExtra("mobile");
        realname = getIntent().getStringExtra("realname");
        head_pic = getIntent().getStringExtra("head_pic");
        tvNickname.setText(realname);

        RequestOptions options = new RequestOptions();
        options.error(R.mipmap.space_header);
        Glide.with(mContext).load(head_pic)
                .apply(options)
                .into(ivHeader);

        themeId = R.style.picture_default_style;
        setPermissions();
    }


    @OnClick({R.id.iv_back, R.id.iv_header, R.id.ll_nickname, R.id.ll_mobile, R.id.ll_login_psw, R.id.ll_jiaoyi_psw, R.id.ll_huancun, R.id.ll_about, R.id.ll_version, R.id.btn_sub})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_header:
                setPicutureImage(1, PictureConfig.SINGLE, null, REQUEST_HEADER);
                break;
            case R.id.ll_nickname:
                showEditTextDialog();
                break;
            case R.id.ll_mobile:
                //修改手机号
                Intent mMobileIntent = new Intent(this, ChangeMobile01Activity.class);
                startActivity(mMobileIntent);
                break;
            case R.id.ll_login_psw:
                //修改密码
                Intent mLoginIntent = new Intent(this, LoginPswActivity.class);
                mLoginIntent.putExtra("mobile",mobile);
                startActivity(mLoginIntent);
                break;
            case R.id.ll_jiaoyi_psw:
                //交易密码
                Intent mTranIntent = new Intent(this, TranPswActivity.class);
                startActivity(mTranIntent);
                break;
            case R.id.ll_huancun:

                break;
            case R.id.ll_about:

                break;
            case R.id.ll_version:
                try {
                    int versionCode = APKVersionCodeUtils.getVersionCode(this);
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("version",versionCode);
                    String param = AES.encryptToHexString(jsonObject1.toString());
                    presenter.getUpdataApp(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case R.id.btn_sub:
                //退出登录
                setSignOutApp();
                break;
        }
    }

    //退出登录
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private void setSignOutApp() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("退出登录")
                .setMessage("确定要退出吗？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "退出", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        SharedPreferencesUtils.remove(SettingActivity.this, GlobalConstants.LOGIN_TOKEN);
                        //跳转登录
                        Intent mLoginIntent = new Intent(SettingActivity.this, LoginActivity.class);
                        mLoginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(mLoginIntent);
                        finish();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }


    private void showEditTextDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("修改昵称")
                .setPlaceholder("在此输入您的昵称")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            dialog.dismiss();
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("name", text.toString());
                                String pamam = AES.encryptToHexString(jsonObject.toString());
                                presenter.setNickName(pamam);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            tvNickname.setText(text.toString());
                        } else {
                            Toast.makeText(SettingActivity.this, "请填入昵称", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void onFailer(Throwable throwable) {
    }

    @Override
    public void setNickName(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                String beanData = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(beanData);
                    showToast("修改昵称成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    public void onUpdataImg(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                String beanData = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(beanData);
                    JSONObject rootObject = new JSONObject(result);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 检查版本更新
     * @param infoBean
     */
    @Override
    public void onUpdatApp(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()){
            case 200:
                try {
                    String info = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    UpdateInfo updateInfo = gson.fromJson(info, UpdateInfo.class);
                    if(updateInfo != null){
                        int version = updateInfo.getVersion();
                        if(mVersionCode >= version){
                            showToast("当前版本已是最新版本");
                            return;
                        }

                        String new_version = updateInfo.getNew_version();
                        String apk_file_url = updateInfo.getApk_file_url();
                        String update_log = updateInfo.getUpdate_log();
                        int constraint = updateInfo.getConstraint();

                        String log = "优化了用户体验";
                        if(!TextUtils.isEmpty(update_log)){
                            String[] split = update_log.split("/n");
                            for(int i = 0;i<split.length;i++){
                                log = log +"\n"+split[i];
                            }
                        }

                        UpdateAppUtils.from(SettingActivity.this)
                                .serverVersionCode(version)
                                .serverVersionName(new_version)
                                .apkPath(apk_file_url)
                                .updateInfo(log)
                                .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
                                .showNotification(true)
                                .isForce(constraint==1?true:false) //是否强制更新
//                          .needFitAndroidN(false)
                                .update();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                break;
            default:break;
        }
    }


    /**
     * 设置相关权限
     */
    private void setPermissions() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(SettingActivity.this);
                } else {
                    Toast.makeText(SettingActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }


    /**
     * 打开选择器
     */
    private void setPicutureImage(int maxNum, int mode, List<LocalMedia> selectList, int requestcode) {
        PictureSelector.create(SettingActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(mode)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(requestcode);//结果回调onActivityResult code
    }


    private final int REQUEST_HEADER = 1111;
    private ArrayList<String> mImageList = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_HEADER:
                    //头像
                    String img_Url = getRequestCodeData(data);
                    RequestOptions options = new RequestOptions()
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.ALL);
                    Glide.with(this)
                            .load(img_Url)
                            .apply(options)
                            .into(ivHeader);

//                    Bitmap bm = BitmapFactory.decodeFile(img_Url);
//                    String base64 = Bitmap2StrByBase64(bm);
//                    mImageList.clear();
//                    mImageList.add("data:image/png;base64," + base64);

                    File tempFile = new File(img_Url);
                    String fileName = tempFile.getName();
                    List<MultipartBody.Part> parts = new ArrayList<>();
                    parts.add(toRequestBodyOfImage(tempFile,fileName));
                    parts.add(toRequestBodyOfText("head", "123"));
                    //头像
//                    RequestBody fileRQ = RequestBody.create(MediaType.parse("image/jpg"), tempFile); //multipart/form-data
//                    MultipartBody.Part part = MultipartBody.Part.createFormData("file", fileName, fileRQ);
                    presenter.updataImg(parts);
                    break;
                default:
                    break;
            }
        }
    }

    private MultipartBody.Part toRequestBodyOfText (String keyStr, String value) {
        MultipartBody.Part body = MultipartBody.Part.createFormData(keyStr, value);
        return body;
    }

    private MultipartBody.Part toRequestBodyOfImage(File tempFile, String name){
        RequestBody fileRQ = RequestBody.create(MediaType.parse("image/jpg"), tempFile);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", name, fileRQ);
        return part;
    }

    /**
     * 获取相关data数据
     *
     * @param data
     */
    private String getRequestCodeData(Intent data) {
        String path = "";
        if (data == null) {
            showToast("图片选择失败");
            return "";
        }
        List<LocalMedia> licenseList = PictureSelector.obtainMultipleResult(data);
        if (licenseList != null && licenseList.size() != 0) {
            LocalMedia localMedia = licenseList.get(0);
            if (localMedia.isCut() && !localMedia.isCompressed()) {
                // 裁剪过
                path = localMedia.getCutPath();
            } else if (localMedia.isCompressed() || (localMedia.isCut() && localMedia.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = localMedia.getCompressPath();
            } else {
                // 原图
                path = localMedia.getPath();
            }
            Log.e("选择了图片", path);
        }
        return path;
    }



}
